/**
 * mutations : 是store暴露给外面的实际赋值接口，要求所有的赋值操作都是即时操作，不能有等待或者回调
 *          也就是说mutations里必须是同步函数
 *          - 可以在组件中用mapMutations混合到methods中
 *          - 常规调用方式是this.$store.commit('mutationName',arg)
 *          - 用commit方式可以大致理解成像 git将文件commit到仓库中
 */
import io from 'socket.io-client'
import _ from 'lodash'
import Vue from 'vue'
/* eslint-disable */
export function SOCKET_CONNECTION_STR (state,path) {
    path = path || '/';//默认socket连接到根路径
    state.socket = io(path);
}

export function RTC_CONFIG (state,cfg) {
    console.log(cfg);
    state.rtcConfig = cfg;
} 

export function ROOM_STATES (state,{ roomName,userName,portrait,friends,token,backMM }) {
    roomName && (state.roomName = roomName);
    userName && (state.userName = userName);
    if(friends){
        state.friends = _.map(friends,(f)=>{return {...f,ping:null,pong:null,stream:null}});
    }
    backMM && (state.backMM = backMM);
    portrait && (state.portrait = portrait);
    state.token = token;
}

export function FRIEND_JOINED (state,friend) {
    state.friends.push(friend);
}
export function FRIEND_LEFT (state,friend) {
    //_.remove(state.friends,_.iteratee({name:friend.name}));
    var i = _.findIndex(state.friends,{name:friend.name});
    //关闭对应的连接
    if(state.friends[i].ping)
        state.friends[i].ping.close();
    if(state.friends[i].pong)
        state.friends[i].pong.close();
    i >= 0 && state.friends.splice(i,1);
}
export function FRIEND_PING(state,{ name , peer }) {
    var friend = _.find(state.friends,{name});
    if(!friend) return;
    Vue.set(friend,'ping',peer);
}
export function FRIEND_PONG(state,{ name , peer }) {
    var friend = _.find(state.friends,{name});
    if(!friend) return;
    Vue.set(friend,'pong',peer);
}
export function FRIEND_STREAM(state,{ name, stream }) {
    var friend = _.find(state.friends,{name});
    if(!friend) return;
    stream.getTracks().forEach(t=>console.log(t));
    Vue.set(friend,'stream',stream);
}
export function CAMERA_VIDEO (state,{ stream }) {
    state.localCameraVideoStream = stream;

    var cloneStream = stream && stream.clone();
    if(cloneStream){
        console.log('muteding');
        cloneStream.getAudioTracks().forEach(t=>t.enabled = false);
        console.log('muted!');
    }else if(state.localMutedStream){
        state.localMutedStream.getTracks().forEach(function(track) {
            track.stop();
        });
        if(state.dispalyVideo == state.localMutedStream)
            state.dispalyVideo = null;
    }
    state.localMutedStream = cloneStream;
}
export function DISPALY_VIDEO (state,{ stream }) {
    state.dispalyVideo = stream;
}